#include "winmain.h"
#include "ui_winmain.h"
#include "QSerialPortInfo"
#include "QMessageBox"
#include "QDebug"
#include "QTimer"
#include "QPixmap"
#include "QPainter"
#include <QColor>
#include "protool.h"
#include "ui_updata.h"

bool exit_flag=0;
int data_sum_cnt;
QSerialPort* lidar_serial;
#include <QMessageBox>

Winmain::Winmain(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Winmain)
{
    ui->setupUi(this);
    this->init();

}
Winmain::~Winmain()
{
    delete ui;
    if (lidar_serial->isOpen())
    {
        lidar_serial->close();
    }
    exit_flag=1;
}


void Winmain::init(void)
{
    lidar_serial=new QSerialPort(this);
    protocol_init();
    connect(lidar_serial,&QSerialPort::readyRead,this,&Winmain::SLOT_processUSARTData);
    connect(ui->action_about,&QAction::triggered,[=](bool checked){
        about_ui.show();
    });

    connect(ui->ac_update,&QAction::triggered,[=](bool checked)
    {
       this->updata_ui.show();
       this->updata_ui.setWindowState((this->updata_ui.windowState()&~Qt::WindowMinimized) | Qt::WindowActive);
       this->updata_ui.raise();

    });
    this->refreshLidarComPort();
    this->setFixedSize(QSize(719,345)); //设置窗口固定

}

void Winmain::on_pb_lidar_refresh_com_list_clicked()
{
    this->refreshLidarComPort();
}


void Winmain::refreshLidarComPort(void)
{

    //通过QSerialPortInfo查找可用串口
    ui->cb_lidar_com_port_list->clear();
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
       ui->cb_lidar_com_port_list->addItem(info.portName());
    }

}

void Winmain::on_pb_open_lidar_serial_clicked()
{

    if(ui->pb_open_lidar_serial->text()=="打开串口")
    {
        this->openLidarComPort();
    }
    else
    {
        this->closeLidarComPort();
    }
}



void Winmain::openLidarComPort(void)
{
     if(lidar_serial->isOpen())//如果串口已经打开了 先给他关闭了
      {
            lidar_serial->clear();
            lidar_serial->close();
      }
      lidar_serial->setPortName(ui->cb_lidar_com_port_list->currentText());
      //设置波特率
      lidar_serial->setBaudRate(115200);
      //设置数据位数
      lidar_serial->setDataBits(QSerialPort::Data8);
      lidar_serial->setParity(QSerialPort::NoParity);
      lidar_serial->setStopBits(QSerialPort::OneStop);
      //设置流控制
      lidar_serial->setFlowControl(QSerialPort::NoFlowControl);
      //打开串口
      if(!lidar_serial->open(QIODevice::ReadWrite))
      {
         QMessageBox::about(NULL, "提示", "无法打开串口！");
         return;
      }

      //下拉菜单控件失能
      ui->cb_lidar_com_port_list->setEnabled(false);
      ui->pb_lidar_refresh_com_list->setEnabled(false);
      ui->lb_lidar_serial_state->setText("连接成功");
      ui->pb_open_lidar_serial->setText("关闭串口");
}


void Winmain::closeLidarComPort(void)
{
    //关闭串口
    lidar_serial->close();
    //下拉菜单控件使能
    ui->cb_lidar_com_port_list->setEnabled(true);
    ui->pb_lidar_refresh_com_list->setEnabled(true);
    ui->lb_lidar_serial_state->setText("未连接");
    ui->pb_open_lidar_serial->setText("打开串口");
}



void Winmain::SLOT_processUSARTData(void)
{

      QByteArray temp = lidar_serial -> readAll();
      char * data_p =  temp.data();
      uint16_t size = temp.size();
      protocol_data_recv((uint8_t *)data_p,size);
      receiving_process(this);
      if(temp.at(0)!='S'&&temp.at(1)!='Z')
      {
           ui->te_com->moveCursor(QTextCursor::End);
           ui->te_com->insertPlainText(temp);
      }
//    disconnect(lidar_serial ,SIGNAL(readyRead()),this,SLOT( SLOT_processUSARTData()));// 有数据就直接接收显示
//    while (lidar_serial->waitForReadyRead(5) == true);
//    connect(lidar_serial ,SIGNAL(readyRead()),this,SLOT( SLOT_processUSARTData()));// 有数据就直接接收显示
//    QByteArray info = rx_data.append(lidar_serial -> readAll());//读串口缓区QByteArray数据 关键是append
//    rx_data.clear();
//    int len=info.length();
//     uint8_t *ch;//不要定义成ch[n]
//     ch = (uint8_t *)info.data();
//     if(ch[0]!=0xFA)
//         return;
//     switch (ch[2]) //判断cmd
//     {
//     case 0x01: //参数数据
//         {
//            if(len!=ch[1])
//            {
//                qDebug()<<"长度不等";
//                return;
//            }
//            param_data_pack_t param_data_pack;
//            memcpy(&param_data_pack,&ch[3],sizeof(param_data_pack_t));
//            ui->le_h->setText(QString("%1").arg(param_data_pack.H));
//            ui->le_r->setText(QString("%1").arg(param_data_pack.R));
//            ui->le_id->setText(QString("%1").arg(param_data_pack.id));
//            ui->le_ki->setText(QString("%1").arg(param_data_pack.ki));
//            ui->le_kp->setText(QString("%1").arg(param_data_pack.kp));
//            ui->le_pol->setText(QString("%1").arg(param_data_pack.pole));
//            ui->le_votage->setText(QString("%1").arg(param_data_pack.voltage));
//            ui->le_time_out->setText(QString("%1").arg(param_data_pack.can_time_out));
//            ui->le_mesure_pol->setText(QString("%1").arg(param_data_pack.measure_pole));
//            ui->le_limit_current->setText(QString("%1").arg(param_data_pack.max_current));

//            ui->statusBar->showMessage("读取成功",1000);
//            break;
//         }

//     case 0x03:
//         {
//            ui->statusBar->showMessage("下位机接收成功，FLASH已保存",2000);
//            break;
//         }
//     case 0x04:
//         {
//            ui->statusBar->showMessage("FLASH参数不正常，请重新写入！！",2000);
//            break;
//         }
//     case 0x05:
//         {
//             Data_pack_t Data_pack;
//             memcpy(&Data_pack,ch,len);
//             //this->updata_ui.setVersion(Data_pack.data1);
//             break;
//         }
//     case 0x06:
//         {

//             this->updata_ui.enteredBootloader();
//             qDebug()<<"进入成功";
//             break;
//         }
//     case 0x07:
//         {

//            QMessageBox::information(NULL,  "提示",
//             "更新完成", QMessageBox::Yes, QMessageBox::Yes);
//            this->updata_ui.updateFinish();
//            break;
//         }

//     }
}


void Winmain::on_pb_read_data_clicked()
{
    if(lidar_serial->isOpen()==false)
    {
        ui->statusBar->showMessage("串口没有打开，请打开串口后重试",1000);
        return;
    }

    ui->statusBar->showMessage("请求读取FLASH",1000);
    set_computer_value(READ_PARAM_CMD,NULL,0);
}



void Winmain::on_pb_write_data_clicked()
{
    if(lidar_serial->isOpen()==false)
    {
        ui->statusBar->showMessage("串口没有打开，请打开串口后重试",1000);
        return;
    }
    if(ui->le_h->text().isEmpty()||ui->le_r->text().isEmpty()
       ||ui->le_id->text().isEmpty()|| ui->le_ki->text().isEmpty()
       ||ui->le_kp->text().isEmpty()||ui->le_pol->text().isEmpty()
       ||ui->le_votage->text().isEmpty()||ui->le_time_out->text().isEmpty()
       ||ui->le_mesure_pol->text().isEmpty()||ui->le_limit_current->text().isEmpty())
    {
        ui->statusBar->showMessage("请检查参数合法性",1000);
        return;
    }

    param_data_pack_t param_data_pack;
    param_data_pack.H= ui->le_h->text().toFloat();
    param_data_pack.R= ui->le_r->text().toFloat();
    param_data_pack.id=ui->le_id->text().toInt();
    param_data_pack.ki=ui->le_ki->text().toFloat();
    param_data_pack.kp=ui->le_kp->text().toFloat();
    param_data_pack.pole=ui->le_pol->text().toInt();
    param_data_pack.voltage= ui->le_votage->text().toFloat();
    param_data_pack.can_time_out= ui->le_time_out->text().toFloat();
    param_data_pack.measure_pole = ui->le_mesure_pol->text().toInt();
    param_data_pack.max_current= ui->le_limit_current->text().toFloat();

    set_computer_value(PARAM_SEND_CMD,&param_data_pack,
                       sizeof(param_data_pack_t));

    ui->statusBar->showMessage("写入FLASH",1000);


}


void Winmain::on_pb_reset_clicked()
{
    if(lidar_serial->isOpen()==false)
    {
        ui->statusBar->showMessage("串口没有打开，请打开串口后重试",1000);
        return;
    }

    ui->statusBar->showMessage("复位中",1000);
    set_computer_value(RESET_CMD,NULL,0);
}

void Winmain::on_pb_calibration_clicked()
{
    if(lidar_serial->isOpen()==false)
    {
        ui->statusBar->showMessage("串口没有打开，请打开串口后重试",1000);
        return;
    }

    ui->statusBar->showMessage("校准中",1000);

    set_computer_value(CALIBRATION_CMD,NULL,0);
}

void Winmain::on_pb_set_current_clicked()
{
    if(lidar_serial->isOpen()==false)
    {
        ui->statusBar->showMessage("串口没有打开，请打开串口后重试",1000);
        return;
    }
    float current=(float)ui->sb_set_current->value();
    set_computer_value(CURRENT_SEND_CMD,&current,4);//写入电流
    ui->statusBar->showMessage("写入电流",1000);


}


void Winmain::on_pb_set_current_zero_clicked()
{
    if(lidar_serial->isOpen()==false)
    {
        ui->statusBar->showMessage("串口没有打开，请打开串口后重试",1000);
        return;
    }
    float current=0;
    set_computer_value(CURRENT_SEND_CMD,&current,4);//写入电流
    ui->statusBar->showMessage("停止",1000);

}
